<?php
session_start();
require_once 'db_connect.php';
require_once 'HerbManager.php';

// 检查用户是否已登录
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$herbManager = new HerbManager();
$herbs = $herbManager->getAllHerbs();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量输入药方测试</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        .prescription-item {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            border: 1px solid #e9ecef;
        }
        .test-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <h1 class="text-center mb-4">
                    <i class="bi bi-clipboard-data text-success"></i>
                    批量输入药方功能测试
                </h1>
                
                <div class="alert alert-info">
                    <h5><i class="bi bi-info-circle"></i> 功能说明</h5>
                    <p class="mb-0">这个页面用于测试批量输入药方功能。你可以复制粘贴药方文本，系统会自动解析并添加到计算器中。</p>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 测试区域 -->
            <div class="col-md-6">
                <div class="test-section">
                    <h4><i class="bi bi-flask text-primary"></i> 测试区域</h4>
                    
                    <div class="mb-3">
                        <label class="form-label">选择测试药方：</label>
                        <select class="form-select" id="testPrescriptionSelect">
                            <option value="">请选择...</option>
                            <option value="test1">测试药方1（简单格式）</option>
                            <option value="test2">测试药方2（混合格式）</option>
                            <option value="test3">测试药方3（复杂格式）</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">药方内容：</label>
                        <textarea id="batchPrescriptionInput" class="form-control" rows="8" 
                                  placeholder="请输入药方，例如：&#10;西洋参90g&#10;别直参60g&#10;柴胡90g&#10;当归90g"></textarea>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button class="btn btn-success" type="button" id="parseBatchPrescription">
                            <i class="bi bi-magic"></i> 解析并添加
                        </button>
                        <button class="btn btn-outline-secondary" type="button" id="clearBatchInput">
                            <i class="bi bi-trash"></i> 清空输入
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 结果区域 -->
            <div class="col-md-6">
                <div class="test-section">
                    <h4><i class="bi bi-list-check text-success"></i> 解析结果</h4>
                    
                    <div id="prescriptionItems">
                        <div class="text-muted text-center py-4">
                            <i class="bi bi-inbox display-4"></i>
                            <p class="mt-2">药方项将在这里显示</p>
                        </div>
                    </div>
                    
                    <hr>
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">总计:</h5>
                        <h3 class="mb-0 text-primary" id="prescriptionTotal">¥0.00</h3>
                    </div>
                    
                    <div class="text-center mt-3">
                        <small class="text-muted" id="prescriptionWeight">0g</small>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 测试药方数据 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="bi bi-file-text text-info"></i> 测试药方数据</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <h6>测试药方1（简单格式）</h6>
                                <pre class="bg-light p-2 rounded">西洋参90g
别直参60g
柴胡90g
当归90g</pre>
                            </div>
                            <div class="col-md-4">
                                <h6>测试药方2（混合格式）</h6>
                                <pre class="bg-light p-2 rounded">怀牛膝90g,白茄根90g
紫丹参150g,白芍90g
巴戟天90g 山茱萸90g</pre>
                            </div>
                            <div class="col-md-4">
                                <h6>测试药方3（复杂格式）</h6>
                                <pre class="bg-light p-2 rounded">泽兰90g，菟丝子90g
枸杞子90g，潼沙苑90g
仙茅90g，熟地黄300g
砂仁30g</pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 返回按钮 -->
        <div class="row mt-4">
            <div class="col-12 text-center">
                <a href="index.php" class="btn btn-primary">
                    <i class="bi bi-arrow-left"></i> 返回主页面
                </a>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 测试药方数据
        const testPrescriptions = {
            test1: `西洋参90g
别直参60g
柴胡90g
当归90g`,
            test2: `怀牛膝90g,白茄根90g
紫丹参150g,白芍90g
巴戟天90g 山茱萸90g`,
            test3: `泽兰90g，菟丝子90g
枸杞子90g，潼沙苑90g
仙茅90g，熟地黄300g
砂仁30g`
        };
        
        // 选择测试药方
        document.getElementById('testPrescriptionSelect').addEventListener('change', function() {
            const selected = this.value;
            if (selected && testPrescriptions[selected]) {
                document.getElementById('batchPrescriptionInput').value = testPrescriptions[selected];
            }
        });
        
        // 显示提示信息
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            const container = document.querySelector('.container');
            container.insertBefore(alertDiv, container.firstChild);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // 计算每克价格
        function calculatePricePerGram(herb) {
            if (herb.sale_price) return herb.sale_price / 10;
            if (herb.category_price) return herb.category_price / 250;
            return (herb.purchase_price * 1.2) / 10;
        }
        
        // 更新总计
        function updateTotal() {
            let total = 0;
            let totalWeight = 0;
            
            document.querySelectorAll('.prescription-item').forEach(item => {
                const weight = parseFloat(item.querySelector('.weight-input').value) || 0;
                const pricePerGram = parseFloat(item.querySelector('.price-per-gram').textContent.replace('¥', ''));
                const itemTotal = weight * pricePerGram;
                item.querySelector('.item-total').textContent = `¥${itemTotal.toFixed(2)}`;
                total += itemTotal;
                totalWeight += weight;
            });
            
            document.getElementById('prescriptionTotal').textContent = `¥${total.toFixed(2)}`;
            document.getElementById('prescriptionWeight').textContent = `${totalWeight}g`;
        }
        
        // 批量解析药方
        function parseBatchPrescription(inputText) {
            if (!inputText.trim()) {
                showAlert('warning', '请输入药方内容');
                return;
            }
            
            // 清空现有药方
            document.getElementById('prescriptionItems').innerHTML = '';
            
            // 清理输入文本，支持多种分隔符
            const lines = inputText.split(/[,，\s\n]+/).filter(line => line.trim());
            let successCount = 0;
            let errorCount = 0;
            let errorMessages = [];
            
            lines.forEach(line => {
                const trimmedLine = line.trim();
                if (!trimmedLine) return;
                
                // 解析药材名和用量
                let herbName, weight;
                
                // 尝试匹配 "药材名+数字+g" 格式
                const match1 = trimmedLine.match(/^(.+?)(\d+(?:\.\d+)?)g$/);
                if (match1) {
                    herbName = match1[1].trim();
                    weight = parseFloat(match1[2]);
                } else {
                    // 尝试匹配 "药材名+数字" 格式
                    const match2 = trimmedLine.match(/^(.+?)(\d+(?:\.\d+)?)$/);
                    if (match2) {
                        herbName = match2[1].trim();
                        weight = parseFloat(match2[2]);
                    } else {
                        // 默认格式，假设整个字符串都是药材名
                        herbName = trimmedLine;
                        weight = 100; // 默认用量100g
                    }
                }
                
                if (herbName && weight > 0) {
                    // 模拟药材数据（实际使用时应该查询数据库）
                    const mockHerb = {
                        name: herbName,
                        sale_price: Math.random() * 100 + 10, // 随机价格
                        category_price: Math.random() * 200 + 20,
                        purchase_price: Math.random() * 50 + 5
                    };
                    
                    const pricePerGram = calculatePricePerGram(mockHerb);
                    
                    // 添加到药方中
                    const itemHtml = `
                        <div class="prescription-item d-flex align-items-center" data-name="${herbName}">
                            <div class="fw-bold me-2" style="min-width: 120px;">${herbName}</div>
                            <div class="flex-grow-1">
                                <input type="number" class="form-control form-control-sm weight-input" 
                                       value="${weight}" min="1" step="1" placeholder="用量(g)">
                            </div>
                            <div class="ms-2 text-nowrap">
                                <span class="price-per-gram">¥${pricePerGram.toFixed(3)}/g</span>
                            </div>
                            <div class="ms-3 text-end" style="min-width: 80px;">
                                <span class="item-total">¥${(pricePerGram * weight).toFixed(2)}</span>
                            </div>
                            <button class="btn btn-sm btn-outline-danger ms-3 remove-item">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    `;
                    document.getElementById('prescriptionItems').innerHTML += itemHtml;
                    successCount++;
                } else {
                    errorCount++;
                    errorMessages.push(`格式错误: ${trimmedLine}`);
                }
            });
            
            // 更新总计
            updateTotal();
            
            // 显示结果提示
            setTimeout(() => {
                let message = `成功添加 ${successCount} 味药材`;
                if (errorCount > 0) {
                    message += `，${errorCount} 味药材添加失败`;
                    if (errorMessages.length > 0) {
                        message += `\n失败原因: ${errorMessages.slice(0, 3).join(', ')}`;
                        if (errorMessages.length > 3) {
                            message += `...`;
                        }
                    }
                }
                
                if (errorCount > 0) {
                    showAlert('warning', message);
                } else {
                    showAlert('success', message);
                }
            }, 500);
        }
        
        // 绑定事件
        document.addEventListener('click', function(e) {
            // 删除药方项
            if (e.target.closest('.remove-item')) {
                const prescriptionItem = e.target.closest('.prescription-item');
                prescriptionItem.remove();
                updateTotal();
            }
        });
        
        // 重量输入变化时更新价格
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('weight-input')) {
                updateTotal();
            }
        });
        
        // 批量解析药方按钮
        document.getElementById('parseBatchPrescription').addEventListener('click', function() {
            const inputText = document.getElementById('batchPrescriptionInput').value;
            parseBatchPrescription(inputText);
        });
        
        // 清空批量输入
        document.getElementById('clearBatchInput').addEventListener('click', function() {
            document.getElementById('batchPrescriptionInput').value = '';
        });
        
        // 初始化
        updateTotal();
    </script>
</body>
</html>
